package com.server.exception;

import com.server.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * 异常处理类
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class CommonExceptionAdvice {

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数", e);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"缺少请求参数");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<String> handleMissingServletRequestParameterException(MethodArgumentTypeMismatchException e) {
        log.error("缺少请求参数", e);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"参数类型异常");
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败", e);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"缺少请求参数");
    }

    /**
     * 401 - UNAUTHORIZED
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AccessTokenException.class)
    public Result<String> handleHttpMessageNotReadableException(AccessTokenException e) {
        log.error("认证失败,{}", e.getMessage());
        return Result.error(HttpStatus.UNAUTHORIZED.value(),"认证失败,请重新登录");
    }

    /**
     * 401 - UNAUTHORIZED
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(PermissionException.class)
    public Result<String> handleHttpMessageNotReadableException(PermissionException e) {
        log.error("权限不足,{}", e.getMessage());
        return Result.error(HttpStatus.UNAUTHORIZED.value(),"权限不足");
    }


    /**
     * 500 - INTERNAL_SERVER_ERROR
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(OperationFailException.class)
    public Result<String> handleHttpMessageNotReadableException(OperationFailException e) {
        log.error("操作失败,{}", e.getMessage());
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"操作失败:"+e.getMessage());
    }




    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"缺少请求参数:"+message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e) {
        log.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"参数绑定失败"+message);

    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handleServiceException(ConstraintViolationException e) {
        log.error("参数验证失败", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return Result.error(HttpStatus.BAD_REQUEST.value(),"参数验证失败"+message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Result<String> handleValidationException(ValidationException e) {
        log.error("参数验证失败", e);
        return Result.error(HttpStatus.BAD_REQUEST.value(),"参数验证失败");
    }

    /**
     * 404 - Not Found
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<String> noHandlerFoundException(NoHandlerFoundException e) {
        log.error("Not Found", e);
        return Result.error(HttpStatus.NOT_FOUND.value(),"Not Found="+e);
    }


    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法", e);
        return Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(),"request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result<String> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.error("不支持当前媒体类型", e);
        return Result.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"content_type_not_supported");
    }

    /**
     * 业务层需要自己声明异常的情况
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ServiceException.class)
    public Result<String> handleServiceException(ServiceException e) {
        log.error("业务逻辑异常", e);
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"业务逻辑异常：" + e.getMessage());
    }

    /**
     * 操作数据或库出现异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataDoException.class)
    public Result<String> handleException(DataDoException e) {
        log.error("操作数据库出现异常:", e);
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"操作数据库出现异常");
    }

    /**
    * 500 - Internal Server Error
    *
    */
    /*
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        log.error("通用异常", e);
        return "500通用异常：" + e.getMessage();
    }*/

    /**
     * 获取其它异常。包括500
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> defaultErrorHandler(Exception e){
        log.error("Exception", e);
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"其它异常:" + e.getMessage());
    }

}
